package zcw.com.lib_leet_code;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 朱城委 on 2021/7/14.<br><br>
 *
 * 赎金信
 */
public class Topic383 {
    public static void main(String[] args) {
        Topic383 instance = new Topic383();

        System.out.println(instance.canConstruct("a", "b"));
        System.out.println(instance.canConstruct("aa", "ab"));
        System.out.println(instance.canConstruct("aa", "aab"));
    }

    public boolean canConstruct(String ransomNote, String magazine) {
        int[] map = new int[26];
        for(char ch : magazine.toCharArray()) {
            map[ch - 'a']++;
        }

        for(char ch : ransomNote.toCharArray()) {
            if(map[ch - 'a'] == 0) {
                return false;
            }

            map[ch - 'a']--;
        }

        return true;
    }

    public boolean canConstruct2(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap<>();
        for(char ch : magazine.toCharArray()) {
            if(map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            }
            else {
                map.put(ch, 1);
            }
        }

        for(char ch : ransomNote.toCharArray()) {
            if(!map.containsKey(ch)) {
                return false;
            }

            if(map.get(ch) == 0) {
                return false;
            }
            else {
                map.put(ch, map.get(ch) - 1);
            }
        }

        return true;
    }
}
